﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using Yitter.IdGenerator;
using Yuekao.Domain.BaseReposi;
using Yuekao.Domain.dto;
using Yuekao.Domain.Entitys;

namespace Yuekao.Domain.Step
{
    public class AuditStep : StepBody
    {
        private readonly IBaseRepository<AuditModel> _auditrepository;
        private readonly IBaseRepository<WorkflowInstanceModel> _instancerepository;
        public AuditStep(IBaseRepository<AuditModel> auditrepository, IBaseRepository<WorkflowInstanceModel> instancerepository)
        {
            _auditrepository = auditrepository;
            _instancerepository = instancerepository;
        }
        /// <summary>
        /// 当前审批人id
        /// </summary>
        public long AuditId {  get; set; }
        /// <summary>
        /// 当前审批人名称
        /// </summary>
        public string AuditName {  get; set; }
        public override ExecutionResult Run(IStepExecutionContext context)
        {
            if(!context.ExecutionPointer.EventPublished)
            {
                AuditModel model=new AuditModel();
                model.Id=YitIdHelper.NextId();
                model.WorkflowId = context.Workflow.Id;
                model.StepId=context.Step.ExternalId;
                model.StepName=context.Step.Name;

                model.AuditId =AuditId;
                model.AuditName = AuditName;
                model.State = false;
                _auditrepository.Add(model);

                Thread.Sleep(100);

                var list= _instancerepository.GetValue(x=>x.WorkflowId==context.Workflow.Id);
                list.StepId = context.Step.ExternalId;
                list.StepName = context.Step.Name;
                list.AuditId=AuditId;
                list.AuditName=AuditName;
                list.State = "处理中";
                _instancerepository.Update(list);


                Console.WriteLine($"等待{AuditName}审批");
                return ExecutionResult.WaitForEvent("MyEvent", context.Workflow.Id,DateTime.Now);
            }
            var eventData=context.ExecutionPointer.EventData as AuditInput;
            Console.WriteLine($"{AuditName}审批了,审批意见是:{eventData.Remark},审批类型是:{eventData.AuditType}");
            if(eventData.AuditType=="拒绝")
            {
                context.Workflow.Status = WorkflowStatus.Complete;
                Console.WriteLine($"{AuditName}拒绝了，审批结束");

                var data = _instancerepository.GetValue(x => x.WorkflowId == context.Workflow.Id);
                data.StepId = nameof(EndStep);
                data.StepName = "结束";
                data.AuditId =0;
                data.AuditName = "";
                data.State = $"{AuditName}拒绝了";
                data.CompeltaTime=DateTime.Now;
                _instancerepository.Update(data);

            }

            return ExecutionResult.Next();
        }
    }
}
